import uvicorn
import click
from app.config import settings
import logging
from logging.handlers import RotatingFileHandler
from app.logger_setup import LoggerSetup, LogConfig
from pathlib import Path
import multiprocessing
from typing import Dict, Any

class ServerConfig:
    """服务器配置管理类"""
    
    @staticmethod
    def get_worker_count(env: str) -> int:
        """获取worker数量"""
        if env == 'dev':
            return 1
        return min(4, multiprocessing.cpu_count() + 1)

    @classmethod
    def get_uvicorn_config(cls, env: str, host: str, port: int) -> Dict[str, Any]:
        """获取Uvicorn配置"""
        return {
            "app": "app.main:app",
            "host": host,
            "port": port,
            "log_level": "debug" if env == 'dev' else "info",
            "reload": settings.RELOAD,
            "workers": cls.get_worker_count(env),
            "access_log": True,
            "log_config": None,
            "proxy_headers": True,
            "forwarded_allow_ips": "*"
        }

class LoggingSetup:
    """日志设置管理类"""
    
    @staticmethod
    def setup_uvicorn_access_log(log_dir: Path) -> None:
        """配置Uvicorn访问日志"""
        log_dir.mkdir(exist_ok=True)
        access_log_file = log_dir / "uvicorn_access.log"
        
        handler = RotatingFileHandler(
            access_log_file,
            maxBytes=10 * 1024 * 1024,
            backupCount=5,
            encoding="utf-8"
        )
        handler.setFormatter(logging.Formatter(
            "%(asctime)s - %(levelname)s - %(message)s"
        ))
        
        access_logger = logging.getLogger("uvicorn.access")
        access_logger.addHandler(handler)
        access_logger.propagate = False

@click.command()
@click.option('--env', type=click.Choice(['dev', 'prod']), default='dev',
              help='运行环境 (dev: 开发环境, prod: 生产环境)')
@click.option('--host', default=settings.HOST, help='服务器主机地址')
@click.option('--port', default=settings.PORT, type=int, help='服务器端口')
def run_server(env: str, host: str, port: int) -> None:
    """启动库存管理系统服务器"""
    try:
        # 打印配置信息
        print(f"{'配置信息':=^50}")
        for key, value in settings.dict().items():
            print(f"{key}: {value}")
        print("=" * 50)

        # 初始化日志
        log_config = LogConfig(
            log_file=settings.LOG_FILE,
            log_level=logging.DEBUG if env == 'dev' else logging.INFO,
            backup_count=settings.LOG_BACKUP_COUNT,
            log_to_console=settings.LOG_TO_CONSOLE
        )
        logger_setup = LoggerSetup(log_config)
        logger = logger_setup.initialize_logger()

        # 设置Uvicorn访问日志
        LoggingSetup.setup_uvicorn_access_log(Path("logs"))

        # 获取服务器配置并启动
        config = ServerConfig.get_uvicorn_config(env, host, port)
        uvicorn.run(**config)

    except Exception as e:
        logging.error(f"服务器启动失败: {str(e)}", exc_info=True)
        raise

if __name__ == "__main__":
    run_server()